package com.bjsxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjsxt.domain.Market;
import com.bjsxt.domain.UserFavoriteMarket;
import com.bjsxt.dto.CoinDto;
import com.bjsxt.feign.CoinServiceFeign;
import com.bjsxt.service.MarketService;
import com.bjsxt.service.UserFavoriteMarketService;
import com.bjsxt.vo.MergeDepthVo;
import com.bjsxt.vo.TradeAreaMarketVo;
import com.bjsxt.vo.TradeMarketVo;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjsxt.domain.TradeArea;
import com.bjsxt.mapper.TradeAreaMapper;
import com.bjsxt.service.TradeAreaService;
import org.springframework.util.CollectionUtils;

/**
 * @Description:  ${description}
 * @ClassName:      TradeAreaServiceImpl
 * @Author:  chenyu
 * @Date:    2025/3/19 14:48
 */
 
@Service
public class TradeAreaServiceImpl extends ServiceImpl<TradeAreaMapper, TradeArea> implements TradeAreaService{

    @Autowired
    private MarketService marketService;

    @Autowired
    private UserFavoriteMarketService userFavoriteMarketService;

    @Autowired
    private CoinServiceFeign coinServiceFeign;

    @Override
    public Page<TradeArea> findByPage(Page<TradeArea> page, String name, String status) {
        return page(page,
                new LambdaQueryWrapper<TradeArea>()
                        .like(!StringUtils.isEmpty(name), TradeArea::getName, name) // 名称的查询
                        .eq(!StringUtils.isEmpty(status), TradeArea::getType, status)  // 标题的查询
        );
    }

    @Override
    public List<TradeArea> findAll(Byte status) {
        return list(new LambdaQueryWrapper<TradeArea>()
                .eq(status!=null, TradeArea::getStatus, status));
    }

    @Override
    public List<TradeAreaMarketVo> getTradeAreaMarkets() {
        List<TradeArea> tradeAreas = list(new LambdaQueryWrapper<TradeArea>().eq(TradeArea::getStatus, 1)
        .orderByAsc(TradeArea::getSort));
        if (CollectionUtils.isEmpty(tradeAreas))
            return Collections.emptyList();
        List<TradeAreaMarketVo> tradeAreaMarketVoList = new ArrayList<>();
        for(TradeArea tradeArea : tradeAreas) {
            List<Market> marketList = marketService.getMarketByTradeAreaId(tradeArea.getId());
            if (!CollectionUtils.isEmpty(marketList)) {
                TradeAreaMarketVo vo = new TradeAreaMarketVo();
                vo.setAreaName(tradeArea.getName());
                vo.setMarkets(market2Vos(marketList));
                tradeAreaMarketVoList.add(vo);
            }
        }
        return tradeAreaMarketVoList;
    }

    private List<TradeMarketVo> market2Vos(List<Market> marketList) {
        return marketList.stream().map(this::toConvertVo).collect(Collectors.toList());
    }

    private TradeMarketVo toConvertVo(Market market) {
        TradeMarketVo vo = new TradeMarketVo();
        vo.setImage(market.getImg());
        vo.setName(market.getName());
        vo.setSymbol(market.getSymbol());
        //价格
        vo.setHigh(market.getOpenPrice());
        vo.setLow(market.getOpenPrice());
        vo.setPrice(market.getOpenPrice());
        vo.setCnyPrice(market.getOpenPrice());
        List<CoinDto> coins = coinServiceFeign.findCoins(Arrays.asList(market.getBuyCoinId()));
        if (CollectionUtils.isEmpty(coins) || coins.size() > 1)
            throw new IllegalArgumentException("报价货币错误");
        //价格单位
        vo.setPriceUnit(coins.get(0).getName());//报价货币名称
        //交易额度
        vo.setTradeMin(market.getTradeMin());
        vo.setTradeMax(market.getTradeMax());
        //下单数量
        vo.setNumMin(market.getNumMin());
        vo.setNumMax(market.getNumMax());
        //手续费
        vo.setSellFeeRate(market.getFeeSell());
        vo.setBuyFeeRate(market.getFeeBuy());
        //价格小数位置
        vo.setNumScale(market.getNumScale());
        //排序
        vo.setSort(market.getSort());
        //合并深度
        vo.setMergeDepth(getMergeDepths(market.getMergeDepth()));

        //交易量
        vo.setVolume(BigDecimal.ZERO);
        vo.setAmount(BigDecimal.ZERO);

        return vo;
    }

    private List<MergeDepthVo> getMergeDepths(String mergeDepth) {
        List<MergeDepthVo> mergeDepthVoList = new ArrayList<>();
        String[] split = mergeDepth.split(",");
        if (split.length != 3)
            throw  new IllegalArgumentException("合并深度不合法");
        MergeDepthVo vo = new MergeDepthVo();
        MergeDepthVo vo2 = new MergeDepthVo();
        MergeDepthVo vo3 = new MergeDepthVo();
        vo.setMergeType("MIN");
        vo.setValue(getDepth(Integer.valueOf(split[0])));
        vo2.setMergeType("DEFAULT");
        vo2.setValue(getDepth(Integer.valueOf(split[1])));
        vo3.setMergeType("MAX");
        vo3.setValue(getDepth(Integer.valueOf(split[2])));
        mergeDepthVoList.add(vo);
        mergeDepthVoList.add(vo2);
        mergeDepthVoList.add(vo3);

        return mergeDepthVoList;
    }

    private BigDecimal getDepth(Integer scale) {
        BigDecimal bigDecimal = new BigDecimal(Math.pow(10, scale)); //指数操作
        return BigDecimal.ONE.divide(bigDecimal).setScale(scale, RoundingMode.HALF_UP);
    }

    @Override
    public List<TradeAreaMarketVo> getUserFavoriteMarkets(Long userId) {
        List<UserFavoriteMarket> list = userFavoriteMarketService.list(new LambdaQueryWrapper<UserFavoriteMarket>()
                .eq(UserFavoriteMarket::getUserId, userId));
        if (CollectionUtils.isEmpty(list))
            return Collections.emptyList();
        List<Long> marketIds = list.stream().map(UserFavoriteMarket::getMarketId).collect(Collectors.toList());
        TradeAreaMarketVo tradeAreaMarketVo = new TradeAreaMarketVo();
        List<Market> marketList = marketService.listByIds(marketIds);
        List<TradeMarketVo> tradeMarketVos = market2Vos(marketList);

        tradeAreaMarketVo.setAreaName("自选");
        tradeAreaMarketVo.setMarkets(tradeMarketVos);

        return Lists.newArrayList(tradeAreaMarketVo);
    }
}
